package lxq.asia;


/**
 * 环形队列（保留一个空间）
 */
public class CircularArrayQueue{
    private final int maxSize;

    /**
     *指向最后一个元素下一格
     */
    private int rear;

    /**
     * 指向第一个元素
     */
    private int front;
    private final int[] queue;

    public CircularArrayQueue(int max){
        maxSize=max;
        queue=new int[maxSize];
        rear=0;
        front=0;
    }
    public CircularArrayQueue(){
        this(11);
    }

    public int pop(){
        if (isEmpty()) {
            throw new  RuntimeException("队列为空");
//            return -1;
        }
        var num=queue[front];
        queue[front]=0;
        front=(front+1)%maxSize;
        return num;
    }
    public void push(int num){
        if (isFull()){
//            throw new  RuntimeException("队列已满");
            System.out.println("队列已满");
            return;
        }
        queue[rear]=num;
        rear=(rear+1)%maxSize;
    }
    public boolean isEmpty(){
        return rear==front;
    }

    public boolean isFull(){
        return (rear+1)%maxSize==front;
    }

    public int head(){
        if (isEmpty()){
            throw new  RuntimeException("队列为空");
        }
        return queue[front];
    }

    public int foot(){
        if (isEmpty()){
            throw new  RuntimeException("队列为空");
        }
        return queue[rear-1];
    }

    public void printQueue(){
        if (isEmpty()){
            System.out.println("队列为空");
            return;
        }
//        var tempFront=front;
//        var tempRear=rear;
//        System.out.print("[");
//        while ((tempFront+1)%maxSize<tempRear){
//            System.out.print(" "+queue[tempFront]);
//            tempFront++;
//        }
//        System.out.print(" ]");
        //(尾－头＋表长)%表长
        var size=(rear-front+maxSize)%maxSize;
        System.out.print("[");
        for (int i=0;i<size;i++){
            System.out.print(" "+queue[(front+i)%maxSize]);
        }
        System.out.print(" ]");
    }
}
